#region License
/* Copyright (c) 2011 Maksymilian Mulawa
	
Redistribution and use in source and binary forms, with or without modification, 
 * are permitted provided that the following conditions are met:

   1. Redistributions of source code must retain the above copyright notice, 
 * this list of conditions and the following disclaimer.
   2. Redistributions in binary form must reproduce the above copyright notice, 
 * this list of conditions and the following disclaimer in the documentation 
 * and/or other materials provided with the distribution.
   3. The name of the author may not be used to endorse or promote products 
 * derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED 
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY 
 * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL 
 * THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
 * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE 
 * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, 
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF 
 * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#endregion

using System;
using System.Data;
using System.Data.SqlClient;
using log4net;
using ReplicationExplorer.DomainModel.Distributor.Entities;
using ReplicationExplorer.DomainModel.Infrastructure;
using ReplicationExplorer.DomainModel.Transactions.Entities;
using ReplicationExplorer.DomainModel.Transactions.Repositories;

namespace ReplicationExplorer.Repositories
{
    public class TransactionsRepository : ITransactionsRepository
    {
        private static readonly ILog _log = LogManager.GetLogger(typeof(TransactionsRepository));
        private readonly IDistributorSession _distributorSession;

        public TransactionsRepository(IDistributorSession distributorSession)
        {
            _distributorSession = distributorSession;
        }

        public ReplicationTransaction GetTransactions(DistributionDatabase database, string startTransactionId, string endTransactionId)
        {
            ReplicationTransaction transaction = new ReplicationTransaction();
            try
            {
                using (SqlConnection connection = new SqlConnection(_distributorSession.GetDistributionDatabaseConnectionString(database.Name)))
                {
                    connection.Open();
                
                    SqlCommand cmd = new SqlCommand(ReplicationExplorerSqlQueries.sp_browsereplcmds, connection);
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.CommandTimeout = _distributorSession.SqlQueryTimeoutInSeconds;
                    cmd.Parameters.AddWithValue("@xact_seqno_start", startTransactionId);
                    cmd.Parameters.AddWithValue("@xact_seqno_end", endTransactionId);

                    using (SqlDataReader reader = cmd.ExecuteReader())
                    {
                        bool transactionMetadataSet = false;
                        while (reader.Read())
                        {
                            //Set transaction properties once
                            if(!transactionMetadataSet)
                            {
                                transaction.OriginatorServer = DataReaderHelper.ReadStrting(reader,"originator_srvname");
                                transaction.OriginatorDatabase = DataReaderHelper.ReadStrting(reader, "originator_db");
                                transaction.OriginatorPublicationId = DataReaderHelper.ReadInt(reader, "originator_publication_id");
                                transaction.SequenceNumber = DataReaderHelper.ReadStrting(reader, "xact_seqno");
                                transactionMetadataSet = true;
                            }

                            ReplicationCommand replicationCommand = new ReplicationCommand();
                            replicationCommand.ArticleId = DataReaderHelper.ReadInt(reader, "article_id");
                            replicationCommand.CommandId = DataReaderHelper.ReadInt(reader, "command_id");
                            replicationCommand.CommandType = DataReaderHelper.ReadInt(reader, "type");
                            replicationCommand.PartialCommand = DataReaderHelper.ReadStrting(reader, "partial_command");
                            replicationCommand.CommandText = DataReaderHelper.ReadStrting(reader, "command");

                            transaction.AddCommand(replicationCommand);

                        }
                    }

                }
            }
            catch (Exception e)
            {
                _log.Error(e);
                throw;
            }

            return transaction;
        }

        public ReplicationTransaction GetTransaction(DistributionDatabase database, string transactionId)
        {
            return GetTransactions(database, transactionId, transactionId);
        }

        //public List<ReplicationCommand> GetCommands(DistributionDatabase database, string commandText)
        //{
        //    return null;
        //}

        //public List<ReplicationCommand> GetCommands(DistributionDatabase database, string transactionId, string commandId)
        //{
        //    return null;
        //}

        //public List<ReplicationCommand> GetCommands(Publication publication, string transactionId, string commandId)
        //{
        //    return null;
        //}
    }
}